/*本页面不要使用Jquery*/

var pageX = {}

pageX.MAX_INPUT_LENGTH = 100;
pageX.postData = {};
pageX.isSubmitting = false;//重复提交防护
cmp.ready(function() {// 缓存详情页面数据
    _initPage();
    _bindEvent();
});

// 页面布局
function _initPage() {
    
    initPageBack();
    cmp.i18n.init(_collPath + "/i18n/", "Collaboration", function(){
        
        pageX.winParams = cmp.href.getParam();
        
      //缓存加载
        window.summaryBO = CollUtils.loadCache(CollCacheKey.summary.summaryBO + pageX.winParams.cache_subfix);
        
        _$("title").innerText=cmp.i18n("collaboration.page.lable.button.cancel1");
        
        _$("#content").setAttribute("placeholder", cmp.i18n("collaboration.page.info.whencancel", [cmp.i18n("collaboration.page.lable.button.cancel1")]));
        
        //清空缓存
        document.addEventListener('deletesessioncache', function(e){
           try{
                //删除协同缓存
               CollCacheKey.delCacheKeys(CollCacheKey.summary, pageX.winParams.cache_subfix);
                
                var options = {
                        moduleId:summaryBO["summary"].id,
                        rightId:summaryBO["summary"].rightId,
                        viewState: summaryBO._viewState
                }
                cmp.sui.clearCache(options);
              
                //触发刷新壳数据
                cmp.webViewListener.fire({ 
                    type: 'com.seeyon.m3.ListRefresh', 
                    data: {affairid: summaryBO["summary"].affairId} 
                });
            }catch(e){}
        });
    });
}

// 事件绑定
function _bindEvent() {
    
    _$("#sendBtn").addEventListener("tap", _submit);
    
    //剩余文字显示
    var $content = _$('#content');
    function showContentCount(){
        CollUtils.fnFontCount("#content", "#fontCount", pageX.MAX_INPUT_LENGTH);
    }
    $content.addEventListener('input', showContentCount);
    showContentCount();
}


function initPageBack() {
    
    //cmp控制返回
    cmp.backbutton();
    cmp.backbutton.push(_goBack);
    
    _$("#goBackBtn").addEventListener("tap", _goBack);
}

//返回
function _goBack() {
	
	summaryBO.backIndex = summaryBO.backIndex - 1;
    cmp.storage.save(CollCacheKey.summary.summaryBO + pageX.winParams.cache_subfix, cmp.toJSON(window.summaryBO), true);
    
	WorkFlowDesignerUtil.unLockH5Workflow(summaryBO["summary"].processId, WorkFlowLock.REPEAL_ITEM);
    cmp.href.back(1, null, pageX.winParams.WebviewEvent);
}

//处理成功后返回列表
function _gotoList(){
  //触发删除缓存
    cmp.event.trigger("deletesessioncache", document);
    
    var backN = 1;
    if(window.summaryBO && summaryBO.backIndex){
        backN = backN + summaryBO.backIndex;
    }
    
    cmp.href.back(backN);
}

//提交
function _submit(){
    
    if(_checkCommentIsEmpty()){
        return;
    }
    
    _initDetailWfDesigner();
    
    pageX.postData.content =  CollUtils.getTextDealComment("#content");
    
    if(pageX.isSubmitting){
        return;
    }
    
    pageX.isSubmitting = true;
    
    var workflowCheckParam = {
		event : "BeforeCancel",
		callback : function(flag){
			if(flag){
				confirmOptAndWFTrace(function(){
					var doRepealBack = function() {
						cmp.dialog.loading();
						//撤销协同
						$s.EdocResource.transRepal(summaryBO["summary"].affairId, {}, pageX.postData, errorBuilder({
							success : function(result) {
								cmp.dialog.loading(false);
								pageX.isSubmitting = false;
								
								if(result["error_msg"]){
									_alert(result["error_msg"]);
								}else {
									_gotoList();
								}
							}
						}));
					}
					if(summaryBO.deeReadOnly == "1") {
   					   doRepealBack();
   				   } else {
   					   //表单开发高级
   					   formDevelopAdance4ThirdParty(summaryBO["summary"].bodyType,summaryBO["summary"].affairId,"repeal",CollUtils.getTextDealComment("#content"),null,doRepealBack);
   				   }
				});
			}else{
				pageX.isSubmitting = false;
			}
		},
        formAppId : summaryBO.workflowCheckParam.formAppId,
        formId : summaryBO.workflowCheckParam.formId,
        formOperationId : summaryBO.workflowCheckParam.formOperationId
    };
    pageX.wfDesigner.executeWorkflowBeforeEvent(workflowCheckParam);
}

/**
 * 弹出确认操作和流程追述的对话框
 * @param callBackFn
 */

function confirmOptAndWFTrace(callBackFn){
    
        
    /*'该操作不能恢复，是否进行回退操作？<br>流程追溯';*/
    var _cofirmHtml  = cmp.i18n("collaboration.page.notrollback.confirm.label", [cmp.i18n("collaboration.page.lable.button.cancel1")])
                          +"<br><span class='trace_span'>"+cmp.i18n("collaboration.page.wftrace.label");
    _cofirmHtml+='<input id="isWFTrace" style="color:#2EAEF7" type="checkbox" class="select-put cmp-checkbox2"></span>'
        
    cmp.notification.confirm(_cofirmHtml,function(e){ //e==1是/e==0 否
        
        var isWfTrace = document.querySelector("#isWFTrace");
        pageX.postData["isWFTrace"] = isWfTrace && isWfTrace.checked  ? "1" : "0";
        
        if(e==1){ //是
            callBackFn();
        }else{
            pageX.isSubmitting = false;
        }
    },null, [ cmp.i18n("collaboration.page.lable.button.cancel"), cmp.i18n("collaboration.page.dialog.OK") ],null,null,0);
}

//检查意见是否允许为空
function _checkCommentIsEmpty(){
    
    var ret = false;
    
    if(CollUtils.getTextDealComment("#content").length == 0){
        //{0}附言不能为空
    	_alert(cmp.i18n(("collaboration.action.alert.repalCommon"), [cmp.i18n("collaboration.page.lable.button.cancel1")]));
        ret = true;
    }
    
    return ret;
}

/**
 * 初始化流程编辑
 */
function _initDetailWfDesigner(){
    _initWfDesigner(null, {
        model : "silent"//采用静默模式
    });
}

//结束提交
function _stopSubmitting(){
	pageX.isSubmitting = false;
    return;
}

function _setCommentValue(message, flag){
	if(flag){
		_$("#content").value = message;
	}
}